// import logo from './logo.svg';
import './App.css';
import './react-flow-editor/0.559758e9e7ea0661625b.css'
import React , { useState, useEffect }from 'react';

import { Editor, Node, Config, MenuItem } from './react-flow-editor/index';
import { Connection } from './react-flow-editor/types';
import Graph from "./graph/Graph";
//import TransformNode from "./graph/TransformNode";

// let LogProps = { subscribe: (update: (log: string) => void) => void };
// let LogState = { content: string };

class Log extends React.Component  {
  constructor(props ) {
    super(props);
    this.state = { content: '' };
    props.subscribe(this.update.bind(this));
  }

    update(log ) {
     this.setState({ content: log });
  }

  render() {
    return (
        <div className="log" >
          <p >{this.state.content}</p>
        </div>
    );
  }
}

class NodeAttributes extends React.Component  {
  constructor(props ) {
    super(props);
    this.state = { node: null };
    props.subscribe(this.update.bind(this));
  }

    update(node  ) {
    this.setState({ node: node });
  }

  render() {
    return (
        <div>
          <h2>Node Attributes</h2>
          <p>{this.state.node === null ? 'No node selected' : 'Data: ' + JSON.stringify(this.state.node.payload.data)}</p>
        </div>
    );
  }
}

const node1Factory = (connections ) => ({
  name: 'Node 1',
  id: 'Node_1',
  type: 'node-type-1',
  payload: { h1: 'hello', data: { custom: 'data 1' } },
  inputs: [{
    connection: connections ? connections.input[0] : [],
    name: 'input 1',
    renderer: () => <input style={{ width: '80px' }} type="range" min="1" max="100" className="slider" />
  }],
  outputs: []
});

const node2Factory = (connections ) => ({
  name: 'Node 2',
  id: 'Node_2',
  type: 'node-type-2',
  payload: { h1: 'world', data: { custom: 'data 2' } },
  inputs: [
    { connection: connections ? connections.input[0] : [], name: 'input 1' },
    { connection: connections ? connections.input[1] : [], name: 'input 2' },
    { connection: connections ? connections.input[2] : [], name: 'input 3' }
  ],
  outputs: [
    { connection: connections ? connections.output[0] : [], name: 'output 1' },
    { connection: connections ? connections.output[1] : [], name: 'output 2' },
    { connection: connections ? connections.output[2] : [], name: 'output 3' }
  ]
});

const node3Factory = (connections ) => ({
  name: 'Node 3',
  id: 'Node_3',
  type: 'node-type-3',
  payload: { h1: '!', data: { } },
  inputs: [],
  outputs: [{ connection: connections ? connections.output[0] : [], name: 'output 1' }]
});

const node4Factory = (connections ) => ({
  name: '测试功能',
  id: 'Node_4',
  type: 'node-type-4',
  payload: { h1: '!', data: {   }},
  inputs: [{
    connection: connections ? connections.input[0] : [],
    data:{},
    name: 'input 1',
    renderer: (  s) => <input   onClick={s. updata(s)}style={{ width: '80px' }} type="range" min="1" max="100" className="slider"  />
    ,updata:  (obj) => (event) => {
       obj.data=event.target.value


    }
  }],
  outputs: [{ connection: connections ? connections.output[0] : [], name: 'output 1' }],


});

const node5Factory = (connections ) => ({
  name: 'Node 5 保存',
  id: 'Node_5',
  type: 'node-type-5',
  payload: { h1: '!', data: { } },
  inputs: [

    {
      connection: connections ? connections.input[0] : [],
      data:{},
      name: 'input 1',
      renderer: (  s) => <input  onChange={s. updata(s)}style={{ width: '80px' }} type="file" id="txtFile" />
      ,updata:  (obj) => (event) => {
        obj.data=event.target.value
        var file = event.target.files[0];
        var reader = new FileReader();
        reader.onload = function(e ){
          var contents = e.target .result;
          // 处理文件内容
          console.log(contents)
        }

        reader.readAsText(file);

      }
    }

  ],
  outputs: [{ connection: connections ? connections.output[0] : [], name: 'output 1' }]
});
const node6Factory = (connections ) => ({
  name: '测试功能',
  id: 'Node_4',
  type: 'node-type-4',
  payload: { h1: '!', data: {   }},
  inputs: [{
    connection: connections ? connections.input[0] : [],
    data:{},
    name: 'input 1',
    renderer: (  s) => <input   onClick={s. updata(s)}style={{ width: '80px' }} type="range" min="1" max="100" className="slider"  />
    ,updata:  (obj) =>   (event) => {
      let text =    'xxxxxxxxxxxxxx';// JSON.stringify(data.value)
      let type='txt';
      let filename='test';
      let domElement = document.createElement('a')

      domElement.setAttribute('href', `data:${type},`+ encodeURIComponent(text))

      domElement.setAttribute('download', filename)

        if(document.createEvent) {

          let event = document.createEvent('MouseEvents')

          event.initEvent('click', true, true)

          domElement.dispatchEvent(event)

        }


    }
  }],
  outputs: [{ connection: connections ? connections.output[0] : [], name: 'output 1' }],


});


let node1=node1Factory({
  input: [[{ nodeId: 'Node_2', port: 0 }]]
})
node1.id='Node_1';
let node2=node2Factory({
  input: [[{ nodeId: 'Node_3', port: 0 }]],
  output: [{ nodeId: 'Node_1', port: 0 }]
})
node2.id= 'Node_2'
let node3= node3Factory({
  output: [[{ nodeId: 'Node_2', port: 0 }]]
})

node3.id='Node_3'
let node4 =node3Factory({
  output: [[{ nodeId: 'Node_222' , port: 0 }]]
})
node4.id='Node_4'
const nodes =   [node1,node2,node3,node4]
window.nodes=nodes;
function resolver(node) {
  if (node.payload.type === '') return <h2 />;
  return (
      <p style={{ height: '100px', width: '60px' }}>{node.payload.h1}</p>
  );
}



 let log =  function (log ) {
  this.setState({ content: log });
};
 let attributes = function  (node ) {
   this.setState({ node: node });
 };
const onChanged =    data => {
  if (log === undefined) return;
  if (data.type === 'ConnectionRemoved')
    log(`Connection '${data.id}' was removed.`);
  else if (data.type === 'NodeRemoved')
    log(`Node '${data.id}' was removed.`);
  else if (data.type === 'NodeCreated')
    log(`Node '${data.node.id}' was created.`);
  else if (data.type === 'ConnectionCreated')
    log(`New connection between nodes '${data.input.nodeId}' [${data.input.port}]  and '${data.output.nodeId}' [${data.output.port}] created.`);
  else if (data.type === 'NodeCollapseChanged')
    log(`Collapse state of Node '${data.id}' is now ${data.shouldBeCollapsed}.`);
  else if (data.type === 'NodeSelected') {
    log(`Node selected: '${data.node.id}'.`);
    attributes(data.node);
  }
  else if (data.type === 'NodeDeselected') {
    log(`Node deselected.`);
    attributes(null);
  }
  else if (data.type === 'node-type-4') {
    log(`node-type-4.`);
    attributes(null);
  }
};

const config = {
  resolver,
  connectionType: 'bezier',
  onChanged,
  grid: true,
  demoMode: true,
  direction: 'we'
};

var  menus=null;
function App() {
  var [nodess, setNodess] = useState(nodes);
  var [menuss, setmenus] = useState(menus);

  var testLoad =function () {
    let node3s= node3Factory({
      output: [[{ nodeId: 'Node_2', port: 0 }]]
    })

    node3s.id='Node_3s'
    let node4s =node3Factory({
      output: [[{ nodeId: 'Node_222' , port: 0 }]]
    })
    node4s.id='Node_4s'
    const nodess =   [{
      name: 'Node 1',
      id: 'node-1',
      type: 'node-type-red ',
      payload: {},
      inputs: [
        {connection: [], name: 'input 1'}, {connection: [], name: 'input 2'}
      ],
      outputs: [
        {connection: [{nodeId: 'node-2', port: 0}], name: 'output 1'},
        {connection: [], name: 'output 2 '}
      ],
      properties: {display: 'only-dots'},
      classNames: ['red']
    },
      {
        name: 'Node 2',
        id: 'node-2',
        type: 'node-type-green ',
        payload: {},
        inputs: [{connection: [{nodeId: 'node-1', port: 0}], name: 'input 1'}],
        outputs: [
          {connection: [], name: 'output 1'},
          {connection: [], name: 'output 2 '}
        ],
        properties: {display: 'only-dots'},
        classNames: ['green']
      }]

    debugger
    setNodess(nodess);
  }


  var loadMenu =(obj) => (event) => {
    //obj.data=event.target.value
    var file = event.target.files[0];
    var reader = new FileReader();
    reader.onload = function(e ){
      var code = e.target .result;
      // 处理文件内容
    //  console.log(contents)

      let codeClass=window.babelObj.createCodeObj("xx","xx",code);


      let codeObj= new codeClass.default() ;
        window.menus=codeObj;
      //let objs=new demo();
      let menus=   window.menus.findMenu()
      ;
      const listItems = menus.map((menu) =>
          <MenuItem name={menu.name} factory={menu.factory} />
      )
      setmenus(listItems)
    }

    reader.readAsText(file);

  }
  var loadNode =(obj) => (event) => {
    debugger
    var file = event.target.files[0];
    var reader = new FileReader();
    reader.onload = function(e ){
      var code = e.target .result;
      // 处理文件内容
      //  console.log(contents)
      var nodesJson = JSON.parse(code);


      // const nodess =   [  ]
      // for(let i=0;i<nodesJson.length;i++){
      //   let nodeJson=nodesJson[i];
      //   let node=  window.menus.node1f(nodeJson);
      //   node.id=node.id+i
      //   nodess.push(node)
      // }



      setNodess(nodesJson);
    }
   reader.readAsText(file);


    // 处理文件内容
    //  console.log(contents)






  }
  return (
      <div>
        <div className="flow-menu">
          <input    onChange={  loadMenu() }style={{ width: '80px' }}  type="file" id="txtFile" />
          <dev  onClick={testLoad} >加载菜单</dev >
          <p/>
          <button  onClick={testLoad} >运行</button >
            <p/>
          <input    onChange={  loadNode(this) }style={{ width: '80px' }}  type="file" id="txtFile" />
          <dev  onClick={testLoad} >加载流程</dev >

          <button  onClick={testLoad} >加载流程</button >
          <MenuItem name="Node Type 1" factory={node1Factory} />
          <MenuItem name="Node Type 2" factory={node2Factory} />
          <MenuItem name="Node Type 3" factory={node3Factory} />
          <MenuItem name="Node Type 4" factory={node4Factory} />
          <MenuItem name="打开文本文件" factory={node5Factory} />
          <MenuItem name="保存文件" factory={node6Factory} />
          {menuss}
        </div>
        <Log subscribe={update => log = update} />
        <Editor config={config} nodes={nodess} />
        <div className="node-attributes">
          <NodeAttributes subscribe={update => attributes = update} />
        </div>
      </div>
  );
}

export default App;
